<template>
 <div class="container"> 
    <TodoItem :item="item" :index="key" :key="key" v-for="(item,key) in todoList">
    </TodoItem>
<div class="container">
    <input type="checkbox" v-model="allDone">全选
    <button id="delBtn" @click="clearDoneItem">全部删除</button>
 </div> 
 </div>

</template>

<script>
import TodoItem from './TodoItem.vue'
import eventBus from '@/js/eventBus'
export default {
    name: "TodoBody",
    data() {
        return {
            todoList: [
                { title: "title1", done: false },
                { title: "title2", done: false },
                { title: "title3", done: true },
                { title: "title4", done: true },
                { title: "title5", done: false }
            ],
            allDone:false
        };
    },
    mounted() {
       //从local加载数据
       console.log("从local加载数据")
      this.todoList =  JSON.parse(localStorage.getItem("todoList"))  
      if(this.todoList==null) {  
            console.log("local为null，初始化Array")
        this.todoList = new Array()
      }


        eventBus.$on(eventBus.addItemEvent,(data) => {
          this.todoList.push(data);  
        })
        eventBus.$on(eventBus.changeItemStatus,(index,val)=>{
            this.todoList[index].done=val
        })
    },
    methods:{ 
    clearDoneItem(){
      this.todoList =  this.todoList.filter((val)=>{
            return !val.done
        });
    }
    },
    watch:{
    allDone(val){
        eventBus.$emit(eventBus.changeAllItemStatus,val)
    },
    todoList(list){
     //将数据存储到本地
        console.log("持久化数据到local")
        
       localStorage.setItem("todoList",JSON.stringify(list)) 
    }
    },
    components: { TodoItem }
}
</script>

<style scoped>
.container {
    margin-top: 20px;
}
#delBtn{
    float: right;
}
</style>